﻿package    

{   
		import flash.text.*;

		import com.adobe.serialization.json.JSON;
		
		import com.adobe.crypto.MD5;
		
		import strhelp.StringHelper;
		
        import flash.net.Socket;   

        import flash.events.*;   

        import flash.display.Sprite;   

        import flash.errors.*;   
		
		import flash.external.ExternalInterface;
		
		import flash.utils.Timer; 
		
		import flash.events.TimerEvent;
		
		import flash.net.URLLoader;
		import flash.net.URLRequest;
		
		import myScrollBar;

        public class SocketPhp extends Sprite   

        { 

                private var mysocket:Socket; 
				
				private var connectMsg:String='';
				private var connectLose:Boolean = false;
				private var resStr:String  = '';
				private var cmsg:String='';
				private var cserver:String='';
				private var cport:uint=10000;
				private var reconnect:Boolean=true;
				private var myTimer:Timer;				
				private var strHelper:StringHelper = new StringHelper();
				
				private var loader:URLLoader;
				private var roomid:String;
				private var username:String;
				private var pwd:String;
                public function SocketPhp()   

                {    	
						loginBt.buttonMode=true;
						loginBt.addEventListener(MouseEvent.CLICK,loginHandler); 
						
						sendBt.buttonMode=true;
						sendBt.addEventListener(MouseEvent.CLICK,sendHandler);
						
						loginErrClose.buttonMode=true;
						loginErrClose.addEventListener(MouseEvent.CLICK,closeErrHandler); 
						
						loginPwd.displayAsPassword = true;

 						loginErr.visible =false;
						loginErrClose.visible=false;
						errInfo.visible=false;

						//roll = new myScrollBar;
						//totalTimes
						//Tconnect('{"roomid":"101","uid":"22","username":"2","action":"connect","usertype":"4"}','192.168.1.172',10000);

                }   
				private function sendHandler(event:MouseEvent):void
				{
					var sendStr:String=strHelper.trim(sendT.text.toString());
					if(sendStr=='')
					{
						showErrMsg('msg error');
					}else
					{
						//trace(mysocket.connected);
						if(mysocket.connected==true)
						{
							sendStr = '{"action":"msgChat","actionto":"all","type":"2","msg":"'+sendStr+'"}';
							SendData(sendStr);
						}else{
							showErrMsg('wait for server connect');
						}
					}
				}
				private function closeErrHandler(event:MouseEvent):void
				{
					loginErr.visible =false;
					loginErrClose.visible=false;
					errInfo.visible=false;
				}
				//698d51a19d8a121ce581499d7b701668
				private function loginHandler(event:MouseEvent):void
				{
			
						roomid=strHelper.trim(loginRoomid.text.toString());
						username=strHelper.trim(loginUsername.text.toString());
						pwd = strHelper.trim(loginPwd.text.toString());
						if(roomid=='' || username=='' || pwd=='')
						{
							loginErr.visible =true;
							loginErrClose.visible=true;
							errInfo.visible=true;
							//errInfo.text='Username Or Password Iis Wrong';
						}else
						{
							pwd = MD5.hash(pwd);
							
							//loginBg.visible =false;
							loader = new URLLoader(new URLRequest("http://localhost/login.php?username="+username+"&password="+pwd));
							loader.addEventListener(Event.COMPLETE, completeLoinHandler);

							
						}
						

				}
				private function showErrMsg(showStr:String):void
				{
					loginErr.visible =true;
					loginErrClose.visible=true;
					errInfo.visible=true;
					errInfo.text=showStr;
				}
				private function HideErrMsg():void
				{
					loginErr.visible =false;
					loginErrClose.visible=false;
					errInfo.visible=false;
				}
				private function completeLoinHandler(event:Event):void
				{
					//trace(loader.data);
					if(loader.data=='1')
					{
						loginBg.visible =false;
						loginRoomid.visible=false;
						loginUsername.visible=false;
						loginPwd.visible=false;
						loginBt.visible=false;
						Tconnect('{"roomid":"101","uid":"22","username":"'+username+'","action":"connect","usertype":"4"}','192.168.1.172',10000);

						
						
					}else{
						loginErr.visible =true;
						loginErrClose.visible=true;
						errInfo.visible=true;
						
					}

				}
				
				public function Tconnect(msg:String=null,server:String=null,port:uint=10000)
				{
						cmsg = msg;
						cserver = server;
						cport = port;
						var myTimer:Timer = new Timer(2000, 1);
            			myTimer.addEventListener(TimerEvent.TIMER, waiting);
            			myTimer.start();
						
						
						connectMsg=msg;
				}
				
				public function Rconnect()
				{						
                    	mysocket.connect(cserver,cport);
						
				}
				
                //不让马上连接。防止频繁连接
				private function waiting(event:TimerEvent):void 
				{
										
					mysocket=new Socket(); 
                    mysocket.addEventListener(Event.CONNECT,OnConnect);    //--当连接成功时 
                    mysocket.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler); //连接失败时
                    mysocket.addEventListener(ProgressEvent.SOCKET_DATA , receivedata);   //返回服务器传输回来的数据
                    mysocket.connect(cserver,cport);
					
					myTimer = new Timer(15000, 0);
            		myTimer.addEventListener(TimerEvent.TIMER, timerHandler);
            		myTimer.start();
				}
                private function OnConnect(e:Event):void  
                { 
						mysocket.writeUTFBytes(connectMsg+"\n"); 
						mysocket.flush();//发送数据
                }                
				
				
				private function timerHandler(event:Event):void
				{
						if(mysocket.connected==false && connectLose==false)
						{
								if(reconnect==true){
									ExternalInterface.call("onError",'disconnect');										
									
									Rconnect();
									
								}else{
									ExternalInterface.call("onError",'disconnect');				
									connectLose = true;
								}
						}
			
				}
                private function ioErrorHandler(e:IOErrorEvent):void  

                {   
						ExternalInterface.call("onError",'disconnect');
                        //trace("连接失败");   

                }   

                

                private function receivedata(e:ProgressEvent):void 
                { 
						//trace("收到的字节数"+mysocket.bytesAvailable); 						
                        var msg:String=''; 
						var _readFlag:int=0;
						
                        while (mysocket.bytesAvailable>0) 
                        {     
								msg+=mysocket.readUTFBytes(mysocket.bytesAvailable);
                        }
						if(msg=="close\n"  || msg=='close'){
							reconnect = false;
						}
						
						if(msg.replace("}\n","test")==msg){
								resStr+=msg;
						}else{	
								
								resStr=msg;								
						}
						//trace(resStr);return;
						if(msg.replace("}\n","test")==msg){
						}else{
								var arr:Array = resStr.split("\n");
								trace(arr.length);return;
								for (var i=0;i<arr.length;i++){
										if(arr[i]!='' && arr[i]!="\n"){	
												
												//dealMsg(arr[i]);
										}
								}
								resStr='';
						}
								
						

                }   
				private function dealMsg(backString:String=null):void
				{
						if(backString=='close' || backString=="close\n")
						{
							reconnect = false;
						}
						if(backString!=null && backString!="\n" && backString!=''){
							trace(backString);
							var str:Object= JSON.decode(backString);
							actionMsg(str);		
						
						}
				}
				
				private function actionMsg(obj:Object):void
				{					
					if(obj.type=='connect')
					{
						if(obj.state=="1"){
							totalTimes.appendText(obj.connect+"\n");
						}
					}
					if(obj.type=='userinfo')
					{
						
					}
					if(obj.type=='userlist')
					{
						
					}
					if(obj.type=='msgChat')
					{
						totalTimes.appendText(obj.fromUsername+': '+obj.msgChat+"\n");
					}
				}
					
				
				
				
                public function SendData(fasongStr:String=null):void
				{
						if(mysocket.connected==true){				
								//trace(fasongStr);
                        		mysocket.writeUTFBytes(fasongStr+"\n");  
                       			mysocket.flush();//发送数据
						}else{
				
								//ExternalInterface.call("onError",'disconnect');
						}
				}

                private function bindDomain() : Boolean
       			{
            			var _loc_1:* = loaderInfo.url.toString().toLocaleLowerCase();
            			var _loc_2:Boolean = false;
            			var _loc_3:Array = ["file:///", "http://localhost", "huoshow.com", "http://192.168", "http://121.14.242.133"];
            			var _loc_4:uint = 0;
            			while ( _loc_4 < _loc_3.length )
            			{                
                				if ( _loc_1.indexOf(_loc_3[_loc_4].toString()) >= 0 )
                				{
                    					_loc_2 = true;
                				}
                				_loc_4 = _loc_4 + 1;
            			}
			
            			return _loc_2;
        		}// end function

        }   

}
